﻿using System;
using System.Collections.Generic;

using System.Text;

namespace RoughJs.Ast
{
    /// <summary>
    /// 2010-01-5 ----- 2010-01-29
    /// 陈曦 1.0
    /// Microsoft Public License (Ms-PL)
    ///This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
    ///1. Definitions
    ///The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
    ///A "contribution" is the original software, or any additions or changes to the software.
    ///A "contributor" is any person that distributes its contribution under this license.
    ///"Licensed patents" are a contributor's patent claims that read directly on its contribution.
    ///2. Grant of Rights
    ///(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
    ///(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
    ///3. Conditions and Limitations
    ///(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
    ///(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
    ///(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
    ///(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
    ///(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. 
    /// </summary>
    public class InterpretedFunction : NativeFunction, Script
    {
        public InterpreterData idata;
        public SecurityController securityController;
        public Object securityDomain;
        public Scriptable[] functionRegExps;

        private InterpretedFunction(InterpreterData idata,
                                Object staticSecurityDomain)
        {
            this.idata = idata;

            // Always get Context from the current thread to
            // avoid security breaches via passing mangled Context instances
            // with bogus SecurityController
            Context cx = Context.getContext();
            SecurityController sc = cx.getSecurityController();
            Object dynamicDomain;
            if (sc != null)
            {
                dynamicDomain = sc.getDynamicSecurityDomain(staticSecurityDomain);
            }
            else
            {
                if (staticSecurityDomain != null)
                {
                    throw new ArgumentException();
                }
                dynamicDomain = null;
            }

            this.securityController = sc;
            this.securityDomain = dynamicDomain;
        }
        private InterpretedFunction(InterpretedFunction parent, int index)
        {
            this.idata = parent.idata.itsNestedFunctions[index];
            this.securityController = parent.securityController;
            this.securityDomain = parent.securityDomain;
        }

        public override string getFunctionName()
        {
            return (idata.itsName == null) ? "" : idata.itsName;
            
        }

        public static InterpretedFunction createScript(InterpreterData idata,
                                            Object staticSecurityDomain)
        {
            InterpretedFunction f;
            f = new InterpretedFunction(idata, staticSecurityDomain);
            return f;
        }

        public override Object resumeGenerator(Context cx, Scriptable scope, int operation,
                                 Object state, Object value)
        {
            return Interpreter.resumeGenerator(cx, scope, operation, state, value);
        }

        /// <summary>
        /// 创建一个方法调用
        /// </summary>
        /// <param name="cx"></param>
        /// <param name="scope"></param>
        /// <param name="idata"></param>
        /// <param name="staticSecurityDomain"></param>
        /// <returns></returns>
       public static InterpretedFunction createFunction(Context cx, Scriptable scope,
                                                  InterpreterData idata,
                                                  Object staticSecurityDomain)
        {
            InterpretedFunction f;
            f = new InterpretedFunction(idata, staticSecurityDomain);
            f.initInterpretedFunction(cx, scope);
            return f;
        }

        private void initInterpretedFunction(Context cx, Scriptable scope)
        {
            initScriptFunction(cx, scope);
            if (idata.itsRegExpLiterals != null)
            {
                functionRegExps = createRegExpWraps(cx, scope);
            }
        }

       public Scriptable[] createRegExpWraps(Context cx, Scriptable scope)
        {
            if (idata.itsRegExpLiterals == null) Kit.codeBug();

            RegExpProxy rep = ScriptRuntime.checkRegExpProxy(cx);
            int N = idata.itsRegExpLiterals.Length;
            Scriptable[] array = new Scriptable[N];
            for (int i = 0; i != N; ++i)
            {
                array[i] = rep.wrapRegExp(cx, scope, idata.itsRegExpLiterals[i]);
            }
            return array;
        }

        public static InterpretedFunction createFunction(Context cx, Scriptable scope,
                                              InterpretedFunction parent,
                                              int index)
        {
            InterpretedFunction f = new InterpretedFunction(parent, index);
            f.initInterpretedFunction(cx, scope);
            return f;
        }


        public override object call(Context cx, Scriptable scope, Scriptable thisObj, object[] args)
        {
            if (!ScriptRuntime.hasTopCall(cx))
            {
                return ScriptRuntime.doTopCall(this, cx, scope, thisObj, args);
            }
            return Interpreter.interpret(this, cx, scope, thisObj, args);
        }

        public override string getClassName()
        {
            return (idata.itsName == null) ? "" : idata.itsName;
        }
        public override int getLanguageVersion()
        {
            return idata.languageVersion;
        }
        public override string getEncodedSource()
        {
            return Interpreter.getEncodedSource(idata);
        }
        public override DebuggableScript getDebuggableView()
        {
            return idata;
        }


        public override int getParamCount()
        {
            return idata.argCount;
        }

        public override int getParamAndVarCount()
        {
            return idata.argNames.Length;
        }

        public override string getParamOrVarName(int index)
        {
            return idata.argNames[index];
        }

        #region Script Members

        public object exec(Context cx, Scriptable scope)
        {
            if (!isScript())
            {
                
                throw new Exception();
            }
            if (!ScriptRuntime.hasTopCall(cx))
            {
                
                return ScriptRuntime.doTopCall(
                    this, cx, scope, scope, ScriptRuntime.emptyArgs);
            }
            return Interpreter.interpret(
                this, cx, scope, scope, ScriptRuntime.emptyArgs);
        }

        #endregion

        public bool isScript()
        {
            return idata.itsFunctionType == 0;
        }


        public override bool getParamOrVarConst(int index)
        {
            return idata.argIsConst[index];
        }

    }
}
